#include "v-text.h"


Bool printCharAt(char ch, int x, int y, char attributes)
{
	if(x > WIDTH_TEXT -1 || y > HEIGHT_TEXT -1)
	return false;
	else
	{
		unsigned long offset = y*(80*2) + x*2;
		_farpokeb(_dos_ds, VIDEO_TEXT + offset, ch ); 
		_farpokeb(_dos_ds, VIDEO_TEXT + offset + 1, attributes);
		return true;
	}
}


Bool printStringAt(char *str, int x, int y, char attributes)
{
	if(x + strlen(str) > WIDTH_TEXT -1|| y > HEIGHT_TEXT -1)
	return false;
	else
	{
		int i = 0;
		while(*str != '\0')
		{
		printCharAt(*str,x+i,y,attributes);
		str++;
		i++;
		}
		return true;
	}
}


Bool printIntAt(int num, int x, int y, char attributes){

	if(num == 0){
		printCharAt('0',x,y,attributes);
		return true;
	}

	//colar o numero em um array de inteiros
	int i=0;
	int k=1;
	int num2 =num;
	int i2 = i;
	
	//conta casas decimais
	while(num2 >0)
	{
		num2 = num2 / 10;
		i++;
	}
	//passa o inteiro para o array
	char char_array[i];
	num2 = num;
	i2 = i;
	i =0;
	k = 1;
	while(i < i2)
	{
		k = num2 % 10;
		num2 = num2 / 10;
		char_array[i] = k + '0';
		i++;
	}
	
	if(x+i2 > WIDTH_TEXT -1|| y > HEIGHT_TEXT -1)
	return false;
	else
	{
		k = 0;
		i = i2 -1;
		while(k < i2){
		printCharAt(char_array[i],x+k,y,attributes);
		i--;
		k++;
		}
		return true;
	}
}

Bool drawFrame(char *title, char attributes,int x, int y, int width, int height)
{
	if( x+ width > WIDTH_TEXT -1 || y + height > HEIGHT_TEXT -1|| strlen(title) -2 > width || height < 2)
		return false;
	else
	{
		int i;
		//imprime parte cima frame
		for(i = 0; i < width; i++){
			printCharAt('*',x + i,y,attributes);
		}
		y++;
	
		printCharAt('*',x,y,attributes);
		printStringAt(title,x+((width - (int)(strlen(title)))/2), y, attributes);
		printCharAt('*',x+width-1,y,attributes);
		y++;
		
		i= height -3;
		for(; i != 0; i--)
		{
		    printCharAt('*',x,y,attributes);
		    printCharAt('*',x+width-1,y,attributes);
		    y++;
		}
		
		i = 0;
		for(i = 0; i < width; i++){
			printCharAt('*',x + i,y,attributes);
		}
		
			
		return true;
	}
}


Bool clean_text_screen(){
    
    int i,j;
    for(i =0; i < HEIGHT_TEXT; i++)
        for(j=0; j < WIDTH_TEXT; j++)
          printCharAt(' ',j,i,0);
          
      return true;
}

/** Clear screen with background color
*/
void fillScreen(char background)
{
	int i, j;
	for(i = 0; i < WIDTH_TEXT; i++)
		for(j = 0; j < HEIGHT_TEXT; j++)
			printCharAt(0, i, j, background);
}
